@using Microsoft.AspNetCore.SignalR.Client
@using System.Collections.Concurrent
@using jiuyuan.Hubs
@inject IJSRuntime JS
@inject NavigationManager Navigation
@implements IAsyncDisposable

<style>
    .game-chat {
        position: fixed;
        bottom: 20px;
        right: 20px;
        width: 400px;
        height: 350px;
        background-color: rgba(20, 20, 40, 0.9);
        border: 2px solid #4a2c8d;
        border-radius: 10px;
        display: flex;
        flex-direction: column;
        box-shadow: 0 0 20px rgba(106, 13, 173, 0.5);
        z-index: 1000;
        overflow: hidden;
        min-width: 300px;
        min-height: 200px;
        max-width: 600px;
        max-height: 500px;
    }

    .chat-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 15px;
        background-color: rgba(30, 30, 60, 0.9);
        border-bottom: 1px solid #4a2c8d;
        border-radius: 10px 10px 0 0;
        cursor: move;
        user-select: none;
    }

    .chat-title {
        font-size: 1.1rem;
        color: #b19cd9;
    }

    .chat-controls {
        display: flex;
        gap: 5px;
    }

    .chat-control-btn {
        background: none;
        border: none;
        color: #a0a0e0;
        cursor: pointer;
        font-size: 1rem;
        padding: 2px 5px;
        border-radius: 3px;
        transition: all 0.3s ease;
    }

    .chat-control-btn:hover {
        color: #b19cd9;
        background-color: rgba(106, 13, 173, 0.3);
    }

    .chat-tabs {
        display: flex;
        background-color: rgba(20, 20, 40, 0.9);
        border-bottom: 1px solid #4a2c8d;
    }

    .chat-tab {
        flex: 1;
        padding: 8px 10px;
        text-align: center;
        background-color: rgba(30, 30, 60, 0.8);
        border: none;
        color: #a0a0e0;
        cursor: pointer;
        transition: all 0.3s ease;
        font-size: 0.9rem;
    }

    .chat-tab:first-child {
        border-radius: 0;
    }

    .chat-tab:last-child {
        border-radius: 0;
    }

    .chat-tab.active {
        background-color: rgba(60, 30, 100, 0.9);
        color: #b19cd9;
    }

    .chat-tab:hover {
        background-color: rgba(40, 40, 80, 0.9);
    }

    .chat-messages {
        flex: 1;
        padding: 10px;
        overflow-y: auto;
        font-size: 0.9rem;
        background-color: rgba(10, 10, 20, 0.8);
    }

    .chat-message {
        margin-bottom: 8px;
        padding: 5px;
        border-radius: 5px;
        background-color: rgba(30, 30, 60, 0.5);
        line-height: 1.4;
        word-wrap: break-word;
    }

    .chat-message.world {
        border-left: 3px solid #6a0dad;
    }

    .chat-message.party {
        border-left: 3px solid #0abda7;
    }

    .chat-message.private {
        border-left: 3px solid #ff0055;
    }

    .chat-input-container {
        display: flex;
        padding: 10px;
        border-top: 1px solid #4a2c8d;
        background-color: rgba(20, 20, 40, 0.9);
        border-radius: 0 0 10px 10px;
    }

    .chat-input {
        flex: 1;
        padding: 8px 12px;
        background-color: rgba(30, 30, 60, 0.8);
        border: 1px solid #4a2c8d;
        border-radius: 5px;
        color: #e0e0ff;
        font-size: 0.9rem;
        outline: none;
    }

    .chat-input:focus {
        border-color: #6a0dad;
        box-shadow: 0 0 5px rgba(106, 13, 173, 0.5);
    }

    .chat-send-btn {
        margin-left: 10px;
        background: linear-gradient(to right, #4a2c8d, #6a0dad);
        border: none;
        border-radius: 5px;
        padding: 8px 15px;
        color: white;
        cursor: pointer;
        font-size: 0.9rem;
        transition: all 0.3s ease;
    }

    .chat-send-btn:hover {
        background: linear-gradient(to right, #5a3c9d, #7a1ddd);
        box-shadow: 0 0 10px rgba(106, 13, 173, 0.5);
    }

    .online-players-modal {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: rgba(20, 20, 40, 0.95);
        border: 2px solid #4a2c8d;
        border-radius: 10px;
        padding: 20px;
        z-index: 2000;
        box-shadow: 0 0 30px rgba(106, 13, 173, 0.7);
        min-width: 300px;
        max-width: 500px;
        max-height: 80vh;
        overflow-y: auto;
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #4a2c8d;
    }

    .modal-title {
        font-size: 1.2rem;
        color: #b19cd9;
    }

    .close-modal-btn {
        background: none;
        border: none;
        color: #a0a0e0;
        font-size: 1.2rem;
        cursor: pointer;
        padding: 5px;
        border-radius: 3px;
    }

    .close-modal-btn:hover {
        color: #b19cd9;
        background-color: rgba(106, 13, 173, 0.3);
    }

    .online-players-list {
        max-height: 300px;
        overflow-y: auto;
    }

    .player-item {
        padding: 10px;
        margin-bottom: 8px;
        background-color: rgba(30, 30, 60, 0.8);
        border: 1px solid #4a2c8d;
        border-radius: 5px;
        cursor: pointer;
        transition: all 0.3s ease;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .player-item:hover {
        background-color: rgba(60, 30, 100, 0.9);
        border-color: #6a0dad;
    }

    .player-name {
        font-weight: bold;
        color: #e0e0ff;
    }

    .player-location {
        font-size: 0.8rem;
        color: #a0a0e0;
    }

    .overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1500;
    }

    .no-party-message {
        text-align: center;
        color: #ff6b6b;
        font-style: italic;
        padding: 10px;
    }

    .private-chat-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 5px 10px;
        background-color: rgba(30, 30, 60, 0.8);
        border-radius: 5px;
        margin-bottom: 10px;
    }

    .target-player {
        font-weight: bold;
        color: #b19cd9;
    }

    .select-player-btn {
        background: linear-gradient(to right, #4a2c8d, #6a0dad);
        border: none;
        border-radius: 3px;
        padding: 4px 8px;
        color: white;
        cursor: pointer;
        font-size: 0.8rem;
        transition: all 0.3s ease;
    }

    .select-player-btn:hover {
        background: linear-gradient(to right, #5a3c9d, #7a1ddd);
    }
</style>

<div class="game-chat" id="game-chat" style="display: @(IsVisible ? "flex" : "none");">
    <div class="chat-header" id="chat-header">
        <div class="chat-title">聊天</div>
        <div class="chat-controls">
            <button class="chat-control-btn" @onclick="Minimize">−</button>
            <button class="chat-control-btn" @onclick="Close">×</button>
        </div>
    </div>
    <div class="chat-tabs">
        <button class="chat-tab @(CurrentChannel == "world" ? "active" : "")" @onclick='() => SwitchChannel("world")'>世界</button>
        <button class="chat-tab @(CurrentChannel == "party" ? "active" : "")" @onclick='() => SwitchChannel("party")'>小队</button>
        <button class="chat-tab @(CurrentChannel == "private" ? "active" : "")" @onclick='() => SwitchChannel("private")'>私聊</button>
    </div>
    <div class="chat-messages" id="chat-messages">
        @if (CurrentChannel == "party" && string.IsNullOrEmpty(CurrentPartyId))
        {
            <div class="no-party-message">当前没有队伍，请先加入一个小队</div>
        }
        else
        {
            @if (CurrentChannel == "private" && !string.IsNullOrEmpty(TargetPlayerName))
            {
                <div class="private-chat-header">
                    <span>与 <span class="target-player">@TargetPlayerName</span> 私聊中</span>
                    <button class="select-player-btn" @onclick="ShowOnlinePlayers">更换</button>
                </div>
            }
            else if (CurrentChannel == "private")
            {
                <div class="private-chat-header">
                    <span>私聊</span>
                    <button class="select-player-btn" @onclick="ShowOnlinePlayers">选择玩家</button>
                </div>
            }

            @foreach (var message in FilteredMessages)
            {
                <div class="chat-message @message.Channel">
                    <strong>[@(GetChannelName(message.Channel))] @message.Username:</strong> @message.Content
                </div>
            }
        }
    </div>
    <div class="chat-input-container">
        <input type="text" class="chat-input" id="chat-input" placeholder="输入聊天内容..." @bind="Message" @onkeypress="SendOnEnter">
        <button class="chat-send-btn" @onclick="Send">发送</button>
    </div>
    <div class="chat-resize-handle" id="chat-resize-handle"></div>
</div>

@if (ShowOnlinePlayersModal)
{
    <div class="overlay" @onclick="CloseOnlinePlayersModal"></div>
    <div class="online-players-modal">
        <div class="modal-header">
            <div class="modal-title">在线玩家</div>
            <button class="close-modal-btn" @onclick="CloseOnlinePlayersModal">×</button>
        </div>
        <div class="online-players-list">
            <!-- 添加测试机器人 -->
            <div class="player-item" @onclick="SelectTestRobot">
                <div>
                    <div class="player-name">测试机器人</div>
                    <div class="player-location">系统</div>
                </div>
                <div style="color: #0abda7;">(测试)</div>
            </div>
            
            @if (OnlinePlayers.Any())
            {
                @foreach (var player in OnlinePlayers)
                {
                    <div class="player-item" @onclick='() => SelectPlayerForPrivateChat(player)'>
                        <div>
                            <div class="player-name">@player.玩家名称</div>
                            <div class="player-location">@player.当前位置</div>
                        </div>
                        @if (player.连接ID == CurrentConnectionId)
                        {
                            <div style="color: #0abda7;">(你自己)</div>
                        }
                    </div>
                }
            }
            else if (OnlinePlayers.Count == 0)
            {
                <div class="no-party-message">当前没有其他玩家在线</div>
            }
        </div>
    </div>
}

@code {
    private string Message { get; set; } = "";
    private string CurrentChannel { get; set; } = "world";
    private string CurrentPartyId { get; set; } = ""; // 当前小队ID
    private string TargetPlayerConnectionId { get; set; } = ""; // 私聊目标玩家连接ID
    private string TargetPlayerName { get; set; } = ""; // 私聊目标玩家名称
    private string CurrentConnectionId { get; set; } = ""; // 当前玩家连接ID
    private string CurrentPlayerName { get; set; } = "艾莉丝"; // 当前玩家名称
    private string CurrentLocation { get; set; } = "新手森林"; // 当前位置
    private bool ShowOnlinePlayersModal { get; set; } = false; // 是否显示在线玩家列表

    [Parameter]
    public bool IsVisible { get; set; } 

    [Parameter]
    public bool IsConnected { get; set; }

    // 聊天消息类
    public class ChatMessage
    {
        public string Channel { get; set; } = "";
        public string Username { get; set; } = "";
        public string Content { get; set; } = "";
        public DateTime Timestamp { get; set; }
    }

    // 在线玩家类
    public class OnlinePlayer
    {
        public string 连接ID { get; set; } = "";
        public string 玩家名称 { get; set; } = "";
        public string 当前位置 { get; set; } = "";
        public DateTime 登录时间 { get; set; }
    }

    // 聊天消息列表 - 使用线程安全集合
    private ConcurrentBag<ChatMessage> ChatMessages { get; set; } = new();

    // 在线玩家列表
    private List<OnlinePlayer> OnlinePlayers { get; set; } = [];

    // 过滤后的消息（用于显示）
    private IEnumerable<ChatMessage> FilteredMessages => ChatMessages
        .Where(m => m.Channel == CurrentChannel)
        .OrderBy(m => m.Timestamp)
        .TakeLast(50); // 只显示最近50条消息

    // SignalR连接
    private HubConnection? connection;

    protected override async Task OnInitializedAsync()
    {
        _ = 连接();
        await base.OnInitializedAsync();
    }

    async Task 连接()
    {
        var b = true;
        // 初始化SignalR连接
        while (b)
        {
            await Task.Delay(1000);
            if (IsConnected)
            {
                await InitializeSignalR();
                b = false;
            }
        }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await InitializeDraggableChat();
        }
    }

    // 初始化SignalR连接
    private async Task InitializeSignalR()
    {
        connection = new HubConnectionBuilder()
            .WithUrl(Navigation.ToAbsoluteUri("/gamehub"))
            .Build();

        // 注册客户端方法
        RegisterClientMethods();

        try
        {
            await connection.StartAsync();
            Console.WriteLine("SignalR连接已建立");

            // 连接成功后登录
            await connection.InvokeAsync("玩家登录", CurrentPlayerName, CurrentLocation);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"SignalR连接失败: {ex.Message}");
        }
    }

    // 注册客户端方法
    private void RegisterClientMethods()
    {
        if (connection == null) return;

        connection.On<string, string>("接收世界消息", (用户名, 消息) =>
        {
            var chatMessage = new ChatMessage
            {
                Channel = "world",
                Username = 用户名,
                Content = 消息,
                Timestamp = DateTime.Now
            };
            ChatMessages.Add(chatMessage);
            InvokeAsync(StateHasChanged);
        });

        connection.On<string, string>("接收小队消息", (用户名, 消息) =>
        {
            var chatMessage = new ChatMessage
            {
                Channel = "party",
                Username = 用户名,
                Content = 消息,
                Timestamp = DateTime.Now
            };
            ChatMessages.Add(chatMessage);
            InvokeAsync(StateHasChanged);
        });

        connection.On<string, string>("接收私聊消息", (用户名, 消息) =>
        {
            var chatMessage = new ChatMessage
            {
                Channel = "private",
                Username = 用户名,
                Content = 消息,
                Timestamp = DateTime.Now
            };
            ChatMessages.Add(chatMessage);
            InvokeAsync(StateHasChanged);
        });

        connection.On<string>("连接成功", (连接ID) =>
        {
            CurrentConnectionId = 连接ID;
            InvokeAsync(StateHasChanged);
        });

        connection.On<System.Collections.Generic.List<jiuyuan.Hubs.在线玩家>>("接收在线玩家列表", (players) =>
        {
            OnlinePlayers = players.Select(p => new OnlinePlayer
            {
                连接ID = p.连接ID,
                玩家名称 = p.玩家名称,
                当前位置 = p.当前位置,
                登录时间 = p.登录时间
            }).ToList();
            InvokeAsync(StateHasChanged);
        });

        connection.On<string, string>("玩家加入", (玩家名称, 位置) =>
        {
            // 这里可以添加通知逻辑
            Console.WriteLine($"{玩家名称} 加入了游戏，位置：{位置}");
            // 重新获取在线玩家列表
            _ = connection.InvokeAsync("获取在线玩家列表");
        });

        connection.On<string>("玩家离开", (玩家名称) =>
        {
            // 这里可以添加通知逻辑
            Console.WriteLine($"{玩家名称} 离开了游戏");
            // 重新获取在线玩家列表
            _ = connection.InvokeAsync("获取在线玩家列表");
        });
    }

    // 初始化可拖拽聊天框
    private async Task InitializeDraggableChat()
    {
        await JS.InvokeVoidAsync("eval", @"
            // 拖拽功能
            const chatBox = document.getElementById('game-chat');
            const header = document.getElementById('chat-header');
            const resizeHandle = document.getElementById('chat-resize-handle');

            let isDragging = false;
            let isResizing = false;
            let startX, startY, startWidth, startHeight, startLeft, startTop;

            // 拖拽功能
            header.addEventListener('mousedown', (e) => {
                isDragging = true;
                startX = e.clientX;
                startY = e.clientY;
                startLeft = parseInt(window.getComputedStyle(chatBox).left, 10);
                startTop = parseInt(window.getComputedStyle(chatBox).top, 10);

                document.addEventListener('mousemove', onDrag);
                document.addEventListener('mouseup', stopDrag);
            });

            function onDrag(e) {
                if (!isDragging) return;

                const dx = e.clientX - startX;
                const dy = e.clientY - startY;

                // 计算新位置
                let newLeft = startLeft + dx;
                let newTop = startTop + dy;

                // 限制在窗口范围内
                const maxLeft = window.innerWidth - chatBox.offsetWidth;
                const maxTop = window.innerHeight - chatBox.offsetHeight;

                newLeft = Math.max(0, Math.min(newLeft, maxLeft));
                newTop = Math.max(0, Math.min(newTop, maxTop));

                chatBox.style.left = newLeft + 'px';
                chatBox.style.top = newTop + 'px';
                chatBox.style.right = 'auto'; // 取消right定位
            }

            function stopDrag() {
                isDragging = false;
                document.removeEventListener('mousemove', onDrag);
                document.removeEventListener('mouseup', stopDrag);
            }

            // 调整大小功能
            resizeHandle.addEventListener('mousedown', (e) => {
                isResizing = true;
                startX = e.clientX;
                startY = e.clientY;
                startWidth = parseInt(document.defaultView.getComputedStyle(chatBox).width, 10);
                startHeight = parseInt(document.defaultView.getComputedStyle(chatBox).height, 10);

                document.addEventListener('mousemove', onResize);
                document.addEventListener('mouseup', stopResize);
                e.preventDefault();
            });

            function onResize(e) {
                if (!isResizing) return;

                const width = startWidth + (e.clientX - startX);
                const height = startHeight + (e.clientY - startY);

                // 应用最小和最大尺寸限制
                const minWidth = 300;
                const minHeight = 200;
                const maxWidth = 600;
                const maxHeight = 500;

                chatBox.style.width = Math.max(minWidth, Math.min(width, maxWidth)) + 'px';
                chatBox.style.height = Math.max(minHeight, Math.min(height, maxHeight)) + 'px';
            }

            function stopResize() {
                isResizing = false;
                document.removeEventListener('mousemove', onResize);
                document.removeEventListener('mouseup', stopResize);
            }

            // 防止文本选择
            header.addEventListener('selectstart', (e) => {
                e.preventDefault();
            });
            
            // 暴露创建小队的函数到全局作用域
            window.createParty = function() {
                // 这里可以添加创建小队的逻辑
                console.log('创建小队');
            };
            
            // 暴露加入小队的函数到全局作用域
            window.joinParty = function(partyId) {
                // 这里可以添加加入小队的逻辑
                console.log('加入小队: ' + partyId);
            };
            
            // 暴露离开小队的函数到全局作用域
            window.leaveParty = function(partyId) {
                // 这里可以添加离开小队的逻辑
                console.log('离开小队: ' + partyId);
            };
        ");
    }

    // 切换聊天频道
    private void SwitchChannel(string channel)
    {
        CurrentChannel = channel;
        
        // 如果切换到私聊频道且还没有选择目标玩家，显示在线玩家列表
        if (channel == "private" && string.IsNullOrEmpty(TargetPlayerName))
        {
            ShowOnlinePlayers();
        }
    }

    // 发送聊天消息
    private async Task Send()
    {
        if (string.IsNullOrEmpty(Message) || connection == null || connection.State != HubConnectionState.Connected)
        {
            return;
        }

        try
        {
            switch (CurrentChannel)
            {
                case "world":
                    await connection.InvokeAsync("发送世界消息", CurrentPlayerName, Message);
                    break;
                case "party":
                    if (string.IsNullOrEmpty(CurrentPartyId))
                    {
                        // 添加提示消息
                        var errorMsg = new ChatMessage
                        {
                            Channel = "party",
                            Username = "系统",
                            Content = "当前没有队伍，请先加入一个小队",
                            Timestamp = DateTime.Now
                        };
                        ChatMessages.Add(errorMsg);
                        StateHasChanged();
                        return;
                    }
                    await connection.InvokeAsync("发送小队消息", CurrentPartyId, CurrentPlayerName, Message);
                    break;
                case "private":
                    if (string.IsNullOrEmpty(TargetPlayerConnectionId))
                    {
                        // 添加提示消息
                        var errorMsg = new ChatMessage
                        {
                            Channel = "private",
                            Username = "系统",
                            Content = "请先选择一个玩家进行私聊",
                            Timestamp = DateTime.Now
                        };
                        ChatMessages.Add(errorMsg);
                        StateHasChanged();
                        ShowOnlinePlayers();
                        return;
                    }
                    await connection.InvokeAsync("发送私聊消息", TargetPlayerConnectionId, CurrentPlayerName, Message);
                    break;
            }

            // 清空输入框
            Message = "";

            // 滚动到底部
            await JS.InvokeVoidAsync("eval", @"
                const chatMessages = document.getElementById('chat-messages');
                if (chatMessages) {
                    chatMessages.scrollTop = chatMessages.scrollHeight;
                }
            ");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发送消息失败: {ex.Message}");
        }
    }

    // 处理回车键发送消息
    private async Task SendOnEnter(KeyboardEventArgs e)
    {
        if (e.Key == "Enter")
        {
            await Send();
        }
    }

    // 获取频道名称
    private string GetChannelName(string channel)
    {
        return channel switch
        {
            "world" => "世界",
            "party" => "小队",
            "private" => "私聊",
            _ => "未知"
        };
    }

    // 最小化聊天框
    private void Minimize()
    {
        IsVisible = false;
    }

    // 关闭聊天框
    private void Close()
    {
        IsVisible = false;
    }

    // 显示在线玩家列表
    private void ShowOnlinePlayers()
    {
        ShowOnlinePlayersModal = true;
        // 获取最新的在线玩家列表
        _ = connection?.InvokeAsync("获取在线玩家列表");
    }

    // 关闭在线玩家列表
    private void CloseOnlinePlayersModal()
    {
        ShowOnlinePlayersModal = false;
    }

    // 选择玩家进行私聊
    private void SelectPlayerForPrivateChat(OnlinePlayer player)
    {
        if (player.连接ID == CurrentConnectionId) // 不能选择自己
        {
            // 添加提示消息
            var errorMsg = new ChatMessage
            {
                Channel = "private",
                Username = "系统",
                Content = "不能与自己私聊",
                Timestamp = DateTime.Now
            };
            ChatMessages.Add(errorMsg);
            StateHasChanged();
            
            // 关闭模态框
            ShowOnlinePlayersModal = false;
        }
        else
        {
            TargetPlayerConnectionId = player.连接ID;
            TargetPlayerName = player.玩家名称;
            CurrentChannel = "private";
            ShowOnlinePlayersModal = false;
            StateHasChanged();
        }
    }

    // 选择测试机器人进行私聊
    private void SelectTestRobot()
    {
        TargetPlayerConnectionId = "test_robot";
        TargetPlayerName = "测试机器人";
        CurrentChannel = "private";
        ShowOnlinePlayersModal = false;
        StateHasChanged();
    }

    // 加入小队
    public async Task JoinParty(string partyId)
    {
        CurrentPartyId = partyId;
        await connection?.InvokeAsync("加入小队", partyId);
    }

    // 离开小队
    public async Task LeaveParty()
    {
        if (!string.IsNullOrEmpty(CurrentPartyId))
        {
            await connection?.InvokeAsync("离开小队", CurrentPartyId);
            CurrentPartyId = "";
        }
    }

    // 实现IAsyncDisposable接口，确保正确释放资源
    public async ValueTask DisposeAsync()
    {
        if (connection != null)
        {
            await connection.StopAsync();
            await connection.DisposeAsync();
        }
    }
}